//
//  ZkjNetworkTool.swift
//  AFN的简单封装
//
//  Created by ZKJ on 2017/9/3.
//  Copyright © 2017年 ZKJ. All rights reserved.
//

import AFNetworking

// MARK:- 定义枚举请求类型(OC枚举只能是int类型，但是swift可以是多种类型)
enum RequestType : String {
    case get = "get"
    case post = "post"
}

class ZkjNetworkTool: AFHTTPSessionManager {
    // 单例，let默认是线程安全的
    static let shareInstance : ZkjNetworkTool = {
        let tool = ZkjNetworkTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tool
    }()
}

// MARK:- 封装网络请求
extension ZkjNetworkTool {
    func zkjRequest(requestType : RequestType, urlString : String, parameters : [String : Any], finishedCallBack : @escaping (_ success : Any?, _ failure : NSError?) -> ()) {
        
        // 请求成功的闭包
        let success = { (task : URLSessionDataTask, result : Any?) in
            finishedCallBack(result!, nil)
        }
        
        // 请求失败的闭包
        let failure = { (task : URLSessionDataTask?, error : Error) in
            finishedCallBack(nil, error as NSError)
        }
        
        // 发送网络请求
        if requestType == .get {
            get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}

// MARK:- 获取授权过的Access Token
extension ZkjNetworkTool {
    func requestToGetAccessToken(code : String, finishedCallBack : @escaping (_ success : [String : Any]?, _ error : NSError?) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        zkjRequest(requestType: .post, urlString: urlString, parameters: parameters) { (result, error) in
            finishedCallBack(result as? [String : Any], error)
        }
    }
}

// MARK:- 获取用户登录信息
extension ZkjNetworkTool {
    func requestToGetUserInfo(access_token : String, uid : String, finishedCallBack : @escaping (_ result : [String : Any]?, _ error : NSError?) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token" : access_token, "uid" : uid]
        zkjRequest(requestType: .get, urlString: urlString, parameters: parameters) { (result, error) in
            finishedCallBack(result as? [String : Any], error)
        }
    }
}

// MARK:- 获取当前登录用户及其所关注用户的最新微博
extension ZkjNetworkTool {
    func requestToHomeTimeLine(since_id : Int64, max_id : Int64, finishedCallBack : @escaping (_ result : [[String : Any]]?, _ error : NSError?) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let access_token = (UserInfoViewModel.sharInstance.userInfo?.access_token)!
        let parameters = ["access_token" : access_token, "since_id" : "\(since_id)", "max_id" : "\(max_id)"]
        zkjRequest(requestType: .get, urlString: urlString, parameters: parameters) { (result, error) in
            //1.获取字典的数据
            guard let resultDic = result as? [String : Any] else {
                finishedCallBack(nil, error)
                return
            }
            
            //2.将statuses数组回调出去
            finishedCallBack(resultDic["statuses"] as? [[String : Any]], error)
        }
    }
}

// MARK:- 发送文字微博
extension ZkjNetworkTool {
    func sendWordStatus(status : String, isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let access_token = (UserInfoViewModel.sharInstance.userInfo?.access_token)!
        let parameters = ["access_token" : access_token, "status" : status]
        zkjRequest(requestType: .post, urlString: urlString, parameters: parameters) { (result, error) in
            if result != nil {
                isSuccess(true)
            } else {
                isSuccess(false)
            }
        }
    }
}

// MARK:- 发送带图片的微博
extension ZkjNetworkTool {
    func sendWordAndPictureStatus(status : String, image : UIImage, isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        let access_token = (UserInfoViewModel.sharInstance.userInfo?.access_token)!
        let parameters = ["access_token" : access_token, "status" : status]
        post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
            if let imageData = UIImageJPEGRepresentation(image, 0.5) {
                formdata.appendPart(withFileData: imageData, name: "pic", fileName: "zkj.png", mimeType: "image/png")
            }
        }, progress: nil, success: { (_, _) in
            isSuccess(true)
        }) { (_, error) in
            print(error)
        }
    }
}




